package com.hiultra.archive.service.impl;

import com.hiultra.archive.mapper.ArcStorehouseMapper;
import com.hiultra.archive.service.IArcStorehouseService;
import com.hiultra.common.constant.UserConstants;
import com.hiultra.common.core.domain.TreeSelect;
import com.hiultra.common.core.domain.entity.ArcStorehouse;
import com.hiultra.common.core.domain.entity.SysDept;
import com.hiultra.common.core.text.Convert;
import com.hiultra.common.exception.ServiceException;
import com.hiultra.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 库房Service业务层处理
 *
 * @author ls
 * @date 2022-08-22
 */
@Service
public class ArcStorehouseServiceImpl implements IArcStorehouseService {
    @Autowired
    private ArcStorehouseMapper arcStorehouseMapper;

    /**
     * 查询库房
     *
     * @param storehouseId 库房主键
     * @return 库房
     */
    @Override
    public ArcStorehouse selectArcStorehouseByStorehouseId(Long storehouseId) {
        return arcStorehouseMapper.selectArcStorehouseByStorehouseId(storehouseId);
    }

    /**
     * 查询库房列表
     *
     * @param arcStorehouse 库房
     * @return 库房
     */
    @Override
    public List<ArcStorehouse> selectArcStorehouseList(ArcStorehouse arcStorehouse) {
        return arcStorehouseMapper.selectArcStorehouseList(arcStorehouse);
    }

    /**
     * 新增库房
     *
     * @param arcStorehouse 库房
     * @return 结果
     */
    @Override
    public int insertArcStorehouse(ArcStorehouse arcStorehouse) {
        if (0 != arcStorehouse.getParentId()) {
            ArcStorehouse info = arcStorehouseMapper.selectStorehouseById(arcStorehouse.getParentId());
            // 如果父节点不为正常状态,则不允许新增子节点
            if (UserConstants.STOREHOUSE_DISABLE.equals(info.getStatus())) {
                throw new ServiceException("库房停用，不允许新增");
            }
            arcStorehouse.setAncestors(info.getAncestors() + "," + arcStorehouse.getParentId());
        } else {
            arcStorehouse.setAncestors("0");
        }
        return arcStorehouseMapper.insertArcStorehouse(arcStorehouse);
    }

    /**
     * 修改库房
     *
     * @param arcStorehouse 库房
     * @return 结果
     */
    @Override
    public int updateArcStorehouse(ArcStorehouse arcStorehouse) {

        ArcStorehouse newParentStorehouse = arcStorehouseMapper.selectStorehouseById(arcStorehouse.getParentId());
        ArcStorehouse oldStorehouse = arcStorehouseMapper.selectStorehouseById(arcStorehouse.getStorehouseId());
        if (StringUtils.isNotNull(newParentStorehouse) && StringUtils.isNotNull(oldStorehouse)) {
            String newAncestors = newParentStorehouse.getAncestors() + "," + newParentStorehouse.getStorehouseId();
            String oldAncestors = oldStorehouse.getAncestors();
            arcStorehouse.setAncestors(newAncestors);
            updateStorehouseChildren(arcStorehouse.getStorehouseId(), newAncestors, oldAncestors);
        }
        int result = arcStorehouseMapper.updateArcStorehouse(arcStorehouse);
        if (UserConstants.DEPT_NORMAL.equals(arcStorehouse.getStatus()) && StringUtils.isNotEmpty(arcStorehouse.getAncestors())
                && !StringUtils.equals("0", arcStorehouse.getAncestors())) {
            // 如果该库房是启用状态，则启用该库房的所有上级库房
            updateParentStorehouseStatusNormal(arcStorehouse);
        }
        return arcStorehouseMapper.updateArcStorehouse(arcStorehouse);
    }

    /**
     * 修改子元素关系
     *
     * @param storehouseId 被修改的库房ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateStorehouseChildren(Long storehouseId, String newAncestors, String oldAncestors) {
        List<ArcStorehouse> children = arcStorehouseMapper.selectChildrenStorehouseById(storehouseId);
        for (ArcStorehouse child : children) {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0) {
            arcStorehouseMapper.updateStorehouseChildren(children);
        }
    }

    /**
     * 修改该库房的父级部门状态
     *
     * @param storehouse 当前库房
     */
    private void updateParentStorehouseStatusNormal(ArcStorehouse storehouse) {
        String ancestors = storehouse.getAncestors();
        Long[] storehouseIds = Convert.toLongArray(ancestors);
        arcStorehouseMapper.updateStorehouseStatusNormal(storehouseIds);
    }

    /**
     * 批量删除库房
     *
     * @param storehouseIds 需要删除的库房主键
     * @return 结果
     */
    @Override
    public int deleteArcStorehouseByStorehouseIds(Long[] storehouseIds) {
        return arcStorehouseMapper.deleteArcStorehouseByStorehouseIds(storehouseIds);
    }

    /**
     * 删除库房信息
     *
     * @param storehouseId 库房主键
     * @return 结果
     */
    @Override
    public int deleteArcStorehouseByStorehouseId(Long storehouseId) {
        return arcStorehouseMapper.deleteArcStorehouseByStorehouseId(storehouseId);
    }

    /**
     * 构建前端所需要树结构
     *
     * @param storehouses 部门列表
     * @return 树结构列表
     */
    @Override
    public List<ArcStorehouse> buildStorehouseTree(List<ArcStorehouse> storehouses) {
        List<ArcStorehouse> returnList = new ArrayList<ArcStorehouse>();
        List<Long> tempList = new ArrayList<Long>();
        for (ArcStorehouse storehouse : storehouses) {
            tempList.add(storehouse.getStorehouseId());
        }
        for (ArcStorehouse storehouse : storehouses) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(storehouse.getParentId())) {
                recursionFn(storehouses, storehouse);
                returnList.add(storehouse);
            }
        }
        if (returnList.isEmpty()) {
            returnList = storehouses;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param storehouses 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildStorehouseTreeSelect(List<ArcStorehouse> storehouses) {
        List<ArcStorehouse> storehouseTrees = buildStorehouseTree(storehouses);
        return storehouseTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<ArcStorehouse> list, ArcStorehouse t) {
        // 得到子节点列表
        List<ArcStorehouse> childList = getChildList(list, t);
        t.setChildren(childList);
        for (ArcStorehouse tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<ArcStorehouse> getChildList(List<ArcStorehouse> list, ArcStorehouse t) {
        List<ArcStorehouse> tlist = new ArrayList<ArcStorehouse>();
        Iterator<ArcStorehouse> it = list.iterator();
        while (it.hasNext()) {
            ArcStorehouse n = (ArcStorehouse) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getStorehouseId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<ArcStorehouse> list, ArcStorehouse t) {
        return getChildList(list, t).size() > 0;
    }

    /**
     * 校验库房名称是否唯一
     *
     * @param storehouses 库房信息
     * @return 结果
     */
    @Override
    public String checkStorehouseNameUnique(ArcStorehouse storehouses){
        Long storehouseId = StringUtils.isNull(storehouses.getStorehouseId()) ? -1L : storehouses.getStorehouseId();
        ArcStorehouse info = arcStorehouseMapper.checkStoreHouseNameUnique(storehouses.getStorehouseName(), storehouses.getParentId());
        if (StringUtils.isNotNull(info) && info.getStorehouseId().longValue() != storehouseId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }
}